<?php


namespace app\admin\system\controller;


use app\admin\system\logic\MenuLogic;
use app\common\controller\BaseAdminController;
use common\annotation\AuthCode;
use core\utils\TreeUtil;
use support\Response;

class MenuController extends BaseAdminController
{
    protected function init()
    {
        parent::init();
        $this->logic = new MenuLogic();
    }

    protected $noNeedRight = [
        'cascaderList',
    ];

    #[AuthCode("system:menu:list")]
    public function list()
    {
        $where = [];
        $this->form['name'] && $where[] = ['name', 'like', "%{$this->form['name']}%"];
        $this->form['title'] && $where[] = ['title', 'like', "%{$this->form['title']}%"];
        $this->form['status'] && $where[] = ['status', '=', $this->form['status']];
        $query = $this->logic->search($where);
        $query->order([
            'sort' => 'asc',
            'id' => 'desc',
        ]);
        $data = $this->logic->getAll($query);
        $data = array_map(function ($item) {
            $item['meta'] = [
                'title' => $item['title'],
                'type' => $item['type'],
                'icon' => $item['icon'],
                'affix' => !!$item['affix'],
                'hidden' => !!$item['hidden'],
                'fullpage' => !!$item['fullpage'],
                'hiddenBreadcrumb' => !!$item['hiddenBreadcrumb'],
            ];
            return $item;
        }, $data);
        $data = TreeUtil::getTree($data);
        return $this->success($data);
    }

    public function beforeAddOrEdit($type, &$data)
    {
        $meta = $data['meta'] ?? [];
        $data = array_merge($data, $meta);
        parent::beforeAddOrEdit($type, $data);
    }

    /**
     * 保存数据
     * @return Response
     */
    public function add()
    {
        $data = input();
        $meta = $data['meta'] ?? [];
        $data = array_merge($data, $meta);
        if ($this->validate) {
            if (!$this->validate->scene('add')->check($data)) {
                return $this->error($this->validate->getError());
            }
        }
        $model = $this->logic->getModel();
        $result = $model->save($data);
        if ($result) {
            $this->afterUpdate(self::ADD, $data);
            return $this->success([
                'id' => $model->id
            ]);
        } else {
            return $this->error();
        }
    }
}